<template>

	<Layout style="background:#f0f2f5;">

	<Spin fix v-if="!tableData"></Spin>

		<Row>

			<Col span="18" offset="3">

				<div style="padding: 20px 20px 0 20px;">
					<Card style="background:#fff;">
						<Row>
							<Col span="10" style="text-align: left;">
								<Cascader :data="DateInit" transfer v-model="selectDate" :load-data="ttrees" :render-format="format" :clearable="false" change-on-select @on-change="changeDate" style="width: 200px; display: inline-block;"></Cascader>
								<!-- <DatePicker :value="selectDate" format="yyyy-MM-dd" type="date" placeholder="Select date" :clearable="false"  @on-change="changeDate" style="width: 200px"></DatePicker> -->
								<Button type="text" :class="{ active: isActiveDate ==new Date().format('yyyy-MM-dd') }" @click="changeDate(new Date().format('yyyy-MM-dd'))">今日</Button>
								<Button type="text" :class="{ active: isActiveDate ==new Date().format('yyyy-MM') }" @click="changeDate(new Date().format('yyyy-MM'))">本月</Button>
								<Button type="text" :class="{ active: isActiveDate ==new Date().format('yyyy') }" @click="changeDate(new Date().format('yyyy'))">今年</Button>
							</Col>
							<Col span="8" style="text-align: center;">
								<Cascader :data="ensTreeData" transfer :clearable="false" change-on-select
                          @on-change="changeWorkSpace" style="width: 300px; display: inline-block;" v-model="spaceSelect"></Cascader>
							</Col>
							<Col span="6" style="text-align: right;">
								<button type="text" class="ivu-btn" @click="post_carbon_dform()" v-if="buttonSize == 'ReportForm'"><span><i class="ivu-icon ivu-icon-ios-download-outline"></i> 导出报表</span></button>
								<RadioGroup v-model="buttonSize" type="button" @on-change="RadioGroupChange">
									<Radio label="Chart">图表</Radio>
									<Radio label="ReportForm">报表</Radio>
								</RadioGroup>
							</Col>
						</Row>
					</Card>
				</div>

				<div style="padding: 20px 20px 0 20px;" v-if="buttonSize == 'Chart'">
					<Card :bordered="false">
						<p slot="title">汇总</p>
						<Row class-name="block_list">
							<Col v-for="(item, index) in carbon_allin_list" class-name="block_list_item" :key="index" span="6">
								<p>{{ item.type }}</p>
								<h1>{{ item.useNum }}<span>{{item.unit}}</span></h1>
								<div class="block_list_item_Progress">
									<p>{{ item.percent }}</p>
									<Progress :percent="item.useNum/item.planNum*100" hide-info />
								</div>
							</Col>
						</Row>
					</Card>
				</div>

				<div style="padding: 20px;" v-if="buttonSize == 'Chart'">
					<Card :bordered="false">
						<p slot="title">单车</p>
						<Row class-name="block_list">
							<Col v-for="(item, index) in carbon_avgs_list" class-name="block_list_item" :key="index" span="6">
								<p>{{ item.type }}</p>
								<h1>{{ item.useNum }}<span>{{item.unit}}</span></h1>
								<div class="block_list_item_Progress">
									<p>{{ item.percent }}</p>
									<Progress :percent="item.useNum/item.planNum*100" hide-info />
								</div>
							</Col>
						</Row>
					</Card>
				</div>

				<div style="padding: 20px; width: 100%;" v-if="buttonSize == 'ReportForm' && !ReportDetailsStatus">
					<Card :bordered="false">
						<p slot="title">报表</p>
						<Table border :row-class-name="rowClassName" size="small" :columns="columns" :data="tableData"
                   :loading="mainFormLoading"></Table>
					</Card>
				</div>

				<div style="padding: 20px; width: 100%;" v-if="buttonSize == 'ReportForm' && ReportDetailsStatus">
					<Card :bordered="false">
						<p slot="title">报表详情</p>
						<Table border :row-class-name="rowClassName" size="small" :columns="ReportDetails.column"
                   :data="ReportDetails.data" :loading="detailFormLoading"></Table>
					</Card>
				</div>

			</Col>
		</Row>
	</Layout>

</template>

<script>
	import obj from '@/utils/common'
	import axios from 'axios'
	// import data from '@/static/date.json'
	// console.log(data);
	export default {
		name: 'AllCarbon',
		data: function () {
            return {
              mainFormLoading: false,
              detailFormLoading: false,
				buttonSize: 'Chart',
				ReportDetailsStatus: false,
				DateInit: [],
				selectDate: [], // 日期三级联动的时间（格式为数组）
				isActiveDate: '', // 当前选择的时间（格式为字符串）
				carbon_allin_list: new Array(),
				carbon_avgs_list: new Array(),
				columns: [
					{
						title: '时段',
						key: 'time'
					},
					{
						title: '用水量（m³）',
						key: 'water',
						renderHeader: (h, params) => {
							return h('div', [
								h('strong', params.column.title),
								h('Icon', {
									props: {
										type: 'md-eye',
										size: '18'
									},
									on: {
										click: () => {
											this.ReportDetailsStatus = true
											this.formDetail(this.isActiveDate, 'water', this.workSpaceString)
										}
									}
								})
							])
						}
					},
					{
						title: '用电量（kW-h）',
						key: 'electricity',
						renderHeader: (h, params) => {
							return h('div', [
								h('strong', params.column.title),
								h('Icon', {
									props: {
										type: 'md-eye',
										size: '18'
									},
									on: {
										click: () => {
											this.ReportDetailsStatus = true
											this.formDetail(this.isActiveDate, 'electricity', this.workSpaceString)
										}
									}
								})
							])
						}
					},
					{
						title: '燃气量（Nm3）',
						key: 'gas',
						renderHeader: (h, params) => {
							return h('div', [
								h('strong', params.column.title),
								h('Icon', {
									props: {
										type: 'md-eye',
										size: '18'
									},
									on: {
										click: () => {
											this.ReportDetailsStatus = true
											this.formDetail(this.isActiveDate, 'gas', this.workSpaceString)
										}
									}
								})
							])
						}
					},
					{
						title: '用热量（kcal）',
						key: 'heat',
						renderHeader: (h, params) => {
							return h('div', [
								h('strong', params.column.title),
								h('Icon', {
									props: {
										type: 'md-eye',
										size: '18'
									},
									on: {
										click: () => {
											this.ReportDetailsStatus = true
											this.formDetail(this.isActiveDate, 'heat', this.workSpaceString)
										}
									}
								})
							])
						}
					},
					{
						title: '空压量（Nm3）',
						key: 'airPress',
						renderHeader: (h, params) => {
							return h('div', [
								h('strong', params.column.title),
								h('Icon', {
									props: {
										type: 'md-eye',
										size: '18'
									},
									on: {
										click: () => {
											this.ReportDetailsStatus = true
											this.formDetail(this.isActiveDate, 'airPress', this.workSpaceString)
										}
									}
								})
							])
						}
					}
				],
				tableData: [],
				ReportDetails: {},
				ensTreeData: [],
         spaceSelect: [],
				workSpaceString: '电-HD1-HD1总电表（测试）'
            }
		},
		mounted: function () {
			// this.$Spin.show();
			let self = this
			self.yearCalculation(2015, 15)
			self.selectDate.push(new Date().format('yyyy')) // 时间初始化
			self.isActiveDate = self.selectDate.join('-')
			self.ensTree()
			self.post_carbon_allin(self.isActiveDate, self.workSpaceString)
			self.post_carbon_avgs(self.isActiveDate, self.workSpaceString)
			self.post_carbon_form(self.isActiveDate, self.workSpaceString)
		},
		methods: {
			// 年份计算
			yearCalculation: function (initYear, number) {
				let self = this
				for (let i = 0; i <= number; i++) {
					let obj = {}
					obj.value = initYear + i
					obj.value = obj.value.toString()
					obj.label = initYear + i + '年'
					obj.children = []
					obj.loading = false
					self.DateInit.push(obj)
				}
			},
			// 年份获取月份和天
			ttrees: function (item, callback) {
                item.loading = true
				window.myapi.ttrees({year: '2019'}).then((res) => {
					if (res.data.status === 200) {
						item.children = res.data.data[0].children
						item.loading = false
						callback()
					}
				}).catch(function (e) {
					console.log(e)
				})
			},
			// table末行样式
			rowClassName (row, index) {
				let self = this
                if (index === self.tableData.length - 1) {
                    return 'Total-row'
                } else if (index === 3) {
                    return ''
                }
                return ''
			},
			// 车间选择  树形数据
			ensTree: function () {
				let self = this
				window.myapi.ensTree({type: '成本', factory: 'ZZ'}).then(function (res) {
					if (res.data.status === 200) {
						self.ensTreeData = res.data.data
            self.spaceSelect.push(res.data.data[0].value)
            // self.carbon_allin_list = res.data.data
					} else {

					}
				}).catch(function (e) {
					console.log(e)
				})
			},
			// xxx能耗总揽--汇总
			post_carbon_allin: function (time, workSpace) {
				let self = this
				window.myapi.carbon_allin({time: time, workSpace: workSpace}).then(function (res) {
					if (res.data.status === 200) {
						self.carbon_allin_list = res.data.data
					} else {

					}
				}).catch(function (e) {
					console.log(e)
				})
			},
			// xxx能耗总揽--单车
			post_carbon_avgs: function (time, workSpace) {
				let self = this
				window.myapi.carbon_avgs({time: time, workSpace: workSpace}).then(function (res) {
					if (res.data.status === 200) {
						self.carbon_avgs_list = res.data.data
					} else {

					}
				}).catch(function (e) {
					console.log(e)
				})
			},
			// xxx能耗总揽--报表
			post_carbon_form: function (time, workSpace) {
				let self = this
        self.mainFormLoading = true
				window.myapi.carbon_form({time: time, workSpace: workSpace}).then(function (res) {
					if (res.data.status === 200) {
						self.tableData = res.data.data
					} else {

					}
				}).catch(function (e) {
					console.log(e)
				}).finally(() => {
          self.mainFormLoading = false
        })
			},
			// xxx能耗总揽--下载报表
			post_carbon_dform: function () {
				/*	let self = this
					window.myapi.carbon_dform({params:self.isActiveDate}).then(function(res){
							console.log(res);
						if (res.data.status === 200) {
						} else {

						}
					}).catch(function (e) {
						console.log(e);
					}) */
				// todo 补充传参
				window.myapi.do_download('$carbon/dform', {time: this.isActiveDate, workSpace: this.workSpace}).then(resp => {
				if (resp.status === 200 && resp.data) {
					let url = window.URL.createObjectURL(new Blob([resp.data], {type: resp.data.type}))

					let filename = decodeURI(resp.headers['content-disposition'].split(';')[1].trim().substr(
					'filename='.length))

					let link = document.createElement('a')
					link.style.display = 'none'
					link.href = url
					link.setAttribute('download', filename)

					document.body.appendChild(link)
					link.click()
				}
				}).finally(() => {
				// this.downLoading = false
				})
			},
			// 时间改变
			changeDate: function (Datetime) {
				let self = this
				self.ReportDetailsStatus = false
				// self.buttonSize = 'Chart';
				if (typeof (Datetime) === 'string') {
					self.isActiveDate = Datetime
					self.selectDate = Datetime.split('-')
				} else {
					self.isActiveDate = Datetime.join('-')
				}
				/* self.post_carbon_allin(self.isActiveDate,self.workSpaceString);
				self.post_carbon_avgs(self.isActiveDate,self.workSpaceString);
				self.post_carbon_form(self.isActiveDate,self.workSpaceString); */
        self.loadDifferDatas()
			},
			// 车间改变
			changeWorkSpace: function (workSpace, selectedData) {
				let self = this
				self.ReportDetailsStatus = false
				// self.buttonSize = 'Chart';
				let str = ''
				for (let i = 0; i < selectedData.length; i++) {
					if (!i) {
						str = selectedData[i].label
					} else {
						str = str + '-' + selectedData[i].label
					}
				}
				self.workSpaceString = str
				self.loadDifferDatas()
			},
      loadDifferDatas () {
        if (this.buttonSize === 'ReportForm') {
          this.post_carbon_form(this.isActiveDate, this.workSpaceString)
        } else {
          this.post_carbon_allin(this.isActiveDate, this.workSpaceString)
          this.post_carbon_avgs(this.isActiveDate, this.workSpaceString)
        }
      },
			// 选择后展示的函数，用于自定义显示格式
			format (labels, selectedData) {
				let str = ''
				for (let i = 0; i < selectedData.length; i++) {
					if (!i) {
						str = selectedData[i].value
					} else {
						str = str + ' - ' + selectedData[i].value
					}
				}
                return str
			},
			// xxx能耗总揽--能耗总揽--报表--能源详情数据
			formDetail: function (time, energy, workSpace) {
				this.detailFormLoading = true
				window.myapi.formDetail({time: time, energy: energy, space: workSpace}).then(res => {
					if (res.data.status === 200) {
						let ReportData = res.data.data
						ReportData.column['0'].renderHeader = (h, params) => {
                return h('div', [
                  h('Icon', {
                    props: {
                      type: 'md-arrow-dropleft-circle',
                      size: '18'
                    },
                    on: {
                      click: () => {
                        this.buttonSize = 'ReportForm'
                        this.ReportDetailsStatus = false
                      }
                    }
                  }),
                  h('strong', params.column.title)
                ])
              }
						this.ReportDetails = ReportData
					} else {
					}
				}).catch(function (e) {
					console.log(e)
				}).finally(() => {
          this.detailFormLoading = false
        })
			},
			RadioGroupChange: function (e) {
				let self = this
				self.ReportDetailsStatus = false
			}
		}
	}
</script>

<style scoped>
.block_list .block_list_item{
	padding: 20px;
	border: 1px solid #e9e9e9;
	margin:0px 0px -1px -1px;
}

.block_list .block_list_item p{
	color: #888;
}

.block_list .block_list_item h1{
	font-weight: 400;
	padding: 15px 15%;
	color: #666;
}

.block_list .block_list_item h1 span{
	font-weight: 200;
	font-size: 16px;
	color: rgba(150, 150, 150, 0.847058823529412);
	margin-left: 10%;
}

.block_list .block_list_item .block_list_item_Progress{
	padding: 0 15%;
}
/deep/ .ivu-table .Total-row td{
	background-color: #f8f8f9;
	font-weight: bold;
}

/deep/ .ivu-table th, /deep/ .ivu-table td{
	text-align: center;
}

/deep/ .ivu-table-header .ivu-table-cell .ivu-icon{
	cursor: pointer;
}

/*滚动条样式*/
/deep/ .ivu-cascader-menu::-webkit-scrollbar {
	width: 6px;
	height: 1px;
}

/deep/ .ivu-cascader-menu::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
	border-radius: 6px;
	-webkit-box-shadow: inset 0 0 3px rgba(0,0,0,0.5);
	background: #888;
}

/deep/ .ivu-cascader-menu::-webkit-scrollbar-track {/*滚动条里面轨道*/
	-webkit-box-shadow: inset 0 0 3px rgba(0,0,0,0.5);
	border-radius: 6px;
	background: #EDEDED;
}

</style>
